package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 会员服务
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;

    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //保存会员信息
    public void add(Member member) {
        String password = member.getPassword();
        if(password != null){
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {//2018.05
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";//2018.05.31
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }
    //任意两个月份之间的会员数量
    @Override
    public Map findMemberCountByMonth2(String startDate, String endDate) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        Calendar min = Calendar.getInstance();
        min.setTime(DateUtils.parseString2Date(startDate,"yyyy-MM"));
        String start = startDate.split("-")[1];
        String end = endDate.split("-")[1];
        String s1 = startDate.split("-")[0];
        String s2 = endDate.split("-")[0];
        int i1 = Integer.parseInt(start);
        int i2 = Integer.parseInt(end);
        int i3 = 0;
        if (s2.equals(s1)){
            i3=i2-i1+1;
        }else {
            i3=(Integer.parseInt(s2)-Integer.parseInt(s1))*(13-i1)+i2;
        }
        for (int i = 0; i < i3; i++) {
            list.add(DateUtils.parseDate2String(min.getTime(),"yyyy.MM"));
            min.add(Calendar.MONTH,1);
        }
        Map<String, List> map = new HashMap<>();
        map.put("months", list);
        ArrayList<Integer> list2 = new ArrayList<>();
        for (String s : list) {
            s=s+".31";
            Integer memberCountBeforeDate = memberDao.findMemberCountBeforeDate(s);
            list2.add(memberCountBeforeDate);
        }
        map.put("memberCount", list2);
        return map;

    }

    @Override
    public Map<String, Object> findMemberCountByYear(String year,String name) {
        Integer count = memberDao.findMemberCountByYear(year);
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("value",count);
        return map;
    }
}
